﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;

using Qs.App.UserManager;
using Qs.Comm;
using Qs.Repository.Domain;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

/// <summary>
/// SingleR服务Hub
/// </summary>
public class ServerHub : Hub
{
    /// <summary>
    /// 已连接的用户信息
    /// </summary>
    public static List<ResAdmin> listUserOnline { get; set; } = new List<ResAdmin>();
    private readonly IHttpContextAccessor _accessor;

    private AppUserManager _appUser;
    public ServerHub(IHttpContextAccessor accessor, AppUserManager appUser)
    {
        _appUser = appUser;
        _accessor = accessor;
    }

    /// <summary>
    /// 当连接成功时执行
    /// </summary>
    /// <returns></returns>
    public override Task OnConnectedAsync()
    {
        string connId = Context.ConnectionId;

        //验证Token
        var token = _accessor.HttpContext.Request.Query["access_token"];

        //连接用户 这里可以存在Redis
        var user = new ResAdmin();
        listUserOnline.Add(user);
        //给当前的连接分组 可以进行同一组接收消息 也可以用Token获取机构权限
        //await Groups.AddToGroupAsync(Context.ConnectionId, "测试组");

        //给当前连接返回消息 .Clients可以发多个连接ID
        Clients.Client(connId).SendAsync("ConnectResponse",
            new Response<ModelAdminUser>()
            {
                Code = 200,
                Result = user,
                Message = user.UserName + "连接成功"
            });

        return base.OnConnectedAsync();
    }

    /// <summary>
    /// 当连接断开时的处理
    /// </summary>
    public override Task OnDisconnectedAsync(Exception exception)
    {
        string connId = Context.ConnectionId;
        var model = listUserOnline.Find(u => u.ConnectionId == connId);
        int count = listUserOnline.RemoveAll(u => u.ConnectionId == connId);
        if (model != null)
        {
            //给当前分组发送消息 在一个分组就能接收到消息
            //Clients.Group(model.GroupName).SendAsync("GetUsersResponse", result);

            //给当前连接返回消息 .Clients可以发多个连接ID
            Clients.Client(connId).SendAsync("DisconnectResponse",
            new Response<bool>()
            {
                Code = 1000,
                Result = true,
                Message = "断开连接"
            });
        }
        return base.OnDisconnectedAsync(exception);
    }

    /// <summary>
    /// 接受用户的数进行推送
    /// </summary>
    /// <returns></returns>
    public async Task SendMessage(string user, string msg)
    {
        Response<ResAdmin> result = new Response<ResAdmin>();
        result.Result = new ResAdmin
        {
            ConnectionId = Context.ConnectionId,
            Token = "",
            UserName = user
        };
        result.Code = 200;
        result.Message = msg;

        //推送给所有连接ID的第一条数据
        await Clients.Clients(listUserOnline.Select(q => q.ConnectionId).ToList()).SendAsync("SendMessage", result);
    }

    public class ResAdmin : ModelAdminUser
    {
        /// <summary>
        /// 连接ID
        /// </summary>
        public string ConnectionId { get; set; }
    }

}